package com.ruoyi.web.controller.module.mer;

import java.util.Date;
import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.mer.MerUser;
import com.ruoyi.system.domain.module.wx.UserMp;
import com.ruoyi.system.domain.module.wx.WxUser;
import com.ruoyi.system.service.module.wx.IUserMpService;
import com.ruoyi.system.service.module.wx.IWxUserService;
import com.ruoyi.system.service.system.ISysUserService;
import com.vdurmont.emoji.EmojiParser;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.module.mer.IMerUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 商家的管理用户wxuser的用户Controller
 *
 * @author ruoyi
 * @date 2022-03-03
 */
@Validated
@Api(value = "商家的管理用户wxuser的用户控制器", tags = {"商家的管理用户wxuser的用户管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/mer/user")
public class MerUserController extends BaseController {

    private final IMerUserService merUserService;
	private final IWxUserService wxUserService;
	private final ISysUserService sysUserService;
	private final IUserMpService userMpService;
	@Value("${ruoyi.imgUrl}")
	private String imgUrl;


	/**
     * 查询商家的管理用户wxuser的用户列表
     */
    @ApiOperation("查询商家的管理用户wxuser的用户列表")
    @PreAuthorize("@ss.hasPermi('module:meruser:list')")
    @GetMapping("/list")
    public TableDataInfo<MerUser> list(@Validated MerUser merUser) {
        QueryWrapper<MerUser> qw = new QueryWrapper<>();
        if(merUser.getMerId()!=null){
        	qw.eq("mer_id",merUser.getMerId());
		}
		if(merUser.getSysUserId()!=null){
			qw.eq("sys_user_id",merUser.getSysUserId());
		}
        TableDataInfo<MerUser> td = PageUtils.buildDataInfo(merUserService.page(PageUtils.buildPage(),qw));
        List<MerUser> list = td.getRows();
        if(CollUtil.isNotEmpty(list)){
        	for (MerUser merUser1 : list){
				SysUser sysUser = sysUserService.getById(merUser1.getSysUserId());
				if(sysUser!=null){
					merUser1.setSysUserName(sysUser.getNickName());
				}

				merUser1.setIsUserMp(0);
				WxUser wxUser = wxUserService.getById(merUser1.getUserId());
				if(wxUser!=null){
					String ss = "";
					QueryWrapper<UserMp> qwMp = new QueryWrapper<>();
					qwMp.eq("union_id",wxUser.getUnionId());
					qwMp.last("limit 1");
					UserMp userMp = userMpService.getOne(qwMp);
					if(userMp != null){
						merUser1.setIsUserMp(1);
						ss = "(已关注公众号)";
					}else{
						ss = "(未关注公众号)";
					}
					merUser1.setWxUserName(EmojiParser.parseToUnicode(wxUser.getNickName()) + ss);

					merUser1.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						merUser1.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
			}
		}
        return td;
    }

    /**
     * 导出商家的管理用户wxuser的用户列表
     */
    @ApiOperation("导出商家的管理用户wxuser的用户列表")
    @PreAuthorize("@ss.hasPermi('module:meruser:export')")
    @Log(title = "商家的管理用户wxuser的用户", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<MerUser> export(@Validated MerUser merUser) {
        List<MerUser> list = merUserService.list();
        ExcelUtil<MerUser> util = new ExcelUtil<>(MerUser.class);
        return util.exportExcel(list, "商家的管理用户wxuser的用户");
    }

    /**
     * 获取商家的管理用户wxuser的用户详细信息
     */
    @ApiOperation("获取商家的管理用户wxuser的用户详细信息")
    @PreAuthorize("@ss.hasPermi('module:meruser:query')")
    @GetMapping("/{id}")
    public AjaxResult<MerUser> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        MerUser merUser = merUserService.getById(id);
        return AjaxResult.success(merUser);
    }

    /**
     * 新增商家的管理用户wxuser的用户
     */
    @ApiOperation("新增商家的管理用户wxuser的用户")
    @PreAuthorize("@ss.hasPermi('module:meruser:add')")
    @Log(title = "商家的管理用户wxuser的用户", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody MerUser merUser) {
        return toAjax(merUserService.save(merUser) ? 1 : 0);
    }

    /**
     * 修改商家的管理用户wxuser的用户
     */
    @ApiOperation("修改商家的管理用户wxuser的用户")
    @PreAuthorize("@ss.hasPermi('module:meruser:edit')")
    @Log(title = "商家的管理用户wxuser的用户", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody MerUser merUser) {
		boolean bl = false;
		QueryWrapper<MerUser> qw = new QueryWrapper<>();
		qw.eq("mer_id",merUser.getMerId());
		qw.eq("sys_user_id",merUser.getSysUserId());
		qw.eq("user_id",merUser.getUserId());
		qw.last("limit 1");
		MerUser user = merUserService.getOne(qw);
		if(user == null){
			user = new MerUser();
			user.setMerId(merUser.getMerId());
			user.setSysUserId(merUser.getSysUserId());
			user.setUserId(merUser.getUserId());
			user.setCreateTime(new Date());
			user.setNickName(merUser.getNickName());
			user.setUserType(0);
			user.setIsAdmin(0);
			user.setState(1);
			bl = merUserService.save(user);
			if(bl){
				return AjaxResult.success("添加成功");
			}else{
				return AjaxResult.error("添加失败");
			}
		}else{
			bl = merUserService.updateById(merUser);
			if(bl){
				return AjaxResult.success("修改成功");
			}else{
				return AjaxResult.error("修改失败");
			}
		}
    }




	/**
	 * 修改商家的管理用户wxuser的用户
	 */
	@ApiOperation("修改商家的管理用户wxuser的用户")
	@PreAuthorize("@ss.hasPermi('module:meruser:edit')")
	@Log(title = "商家的管理用户wxuser的用户", businessType = BusinessType.UPDATE)
	@PostMapping("/updateAdmin")
	public AjaxResult<Void> updateManager(@Validated(EditGroup.class) @RequestBody MerUser merUser) {
		merUserService.update(new LambdaUpdateWrapper<MerUser>()
			.set(MerUser::getIsAdmin,0)
			.eq(MerUser::getMerId,merUser.getMerId()));

		merUser.setIsAdmin(1);
		return toAjax(merUserService.updateById(merUser) ? 1 : 0);
	}


	/**
     * 删除商家的管理用户wxuser的用户
     */
    @ApiOperation("删除商家的管理用户wxuser的用户")
    @PreAuthorize("@ss.hasPermi('module:meruser:remove')")
    @Log(title = "商家的管理用户wxuser的用户" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return toAjax(merUserService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
